import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {Row,Col,Card,Form,Input,Select,Icon,Button,Dropdown,Menu,InputNumber,Modal,message,Badge,Divider,Upload,Radio,label,Table,Popconfirm,} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from '../Mana/Role.less';


const Option = Select.Option;
const { TextArea } = Input;
const Search = Input.Search;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const getValue = obj =>Object.keys(obj).map(key => obj[key]).join(',');

//图片
var headerimg="";
var imageUrl="";
//图片
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
class Avatar extends React.Component {
  state = {  loading: false };
  handleChange = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if(info.file.status === 'done') {
    	headerimg=info.file.response.obj.path;
    	imageUrl=info.file.response.obj.path;
	    getBase64(info.file.originFileObj, imageUrl => this.setState({
	        imageUrl,
	        loading: false,
	    }));
    }
  }
  render() {
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
	  if(imageUrl==undefined){
	  	 imageUrl = this.state.imageUrl;
	  }else{
	  	headerimg=imageUrl;
	  }
    const urls="api/web/attachment/upload.manage?token="+sessionStorage.getItem('token');
    return (
      <Upload
        name="file"
        style={{width:'200px'}}
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action={urls}
        method="POST"
        enctype="multipart/form-data"
        onChange={this.handleChange}
      >
        {imageUrl ? <img src={imageUrl} alt=""  style={{width:'200px'}} /> : uploadButton}
      </Upload>
    );
  }
}


const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible,title,obj} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(fieldsValue.state == undefined) { 	fieldsValue.state = 1}
      if(fieldsValue.remark == undefined) { 	fieldsValue.remark = ""}
     	fieldsValue.icon=headerimg;
	    form.resetFields();
	    handleAdd(title,obj.signinConfigId,fieldsValue);
    });
  };
 const {getFieldDecorator } = form;
  return (
    <Modal
      maskClosable={false}
      destroyOnClose={true}
     title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false,'','')}
    >
   <Form layout="horizontal">
      	<FormItem label="几号"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('numberDay', {
            	initialValue:obj.numberDay,
              	rules: [{ required: true, message: '不能为空!' }],
            })(
              	<Select>
	              <option value="1">1</option>
	              <option value="2">2</option>
	              <option value="3">3</option>
	              <option value="4">4</option>
	              <option value="5">5</option>
	              <option value="6">6</option>
	              <option value="7">7</option>
	              <option value="8">8</option>
	              <option value="9">9</option>
	              <option value="10">10</option>
	              <option value="11">11</option>
	              <option value="12">12</option>
	              <option value="13">13</option>
	              <option value="14">14</option>
	              <option value="15">15</option>
	              <option value="16">16</option>
	              <option value="17">17</option>
	              <option value="18">18</option>
	              <option value="19">19</option>
	              <option value="20">20</option>
	              <option value="21">21</option>
	              <option value="22">22</option>
	              <option value="23">23</option>
	              <option value="24">24</option>
	              <option value="25">25</option>
	              <option value="26">26</option>
	              <option value="27">27</option>
	              <option value="28">28</option>
	              <option value="29">29</option>
	              <option value="30">30</option>
	              <option value="31">31</option>
	          </Select>
            )}
        </FormItem>
       	<FormItem label="奖励类型"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('hortationType', {
            	initialValue:obj.hortationType,
              	rules: [{ required: true, message: '不能为空!' }],
            })(
              	<Select>
	              <option value="1">立方币</option>
	              <option value="2">实物</option>
	            </Select>
            )}
        </FormItem>
        <FormItem label="图标"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {(<Avatar />)}
        </FormItem>

        <FormItem label="奖励"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('hortation', {
            	initialValue:obj.hortation,
              	rules: [{ required: true, message: '不能为空!' }],
            })(
              	<InputNumber placeholder="请输入" />
            )}
        </FormItem>
        <FormItem label="状态"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('state', {
            	initialValue:obj.state==undefined ? "1":obj.state,
              	rules: [{ required: true, message: '不能为空!' }],
            })(
              	<Select>
	              <Option value="1">有效</Option>
              		<Option value="0">无效</Option>
	            </Select>
            )}
        </FormItem>
        <FormItem label="备注"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('remark', {
            	initialValue:obj.remark,
            })(
              	<TextArea></TextArea>
            )}
        </FormItem>
    </Form>
  </Modal>
  );
});



@connect(({ signin, loading }) => ({
  signin,
  loading: loading.models.signin,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    obj: "",
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
       type: 'signin/fetch_Sign',
    });
  }
   handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'areas/findSupplier',
      payload: params,
    });

  };


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
	e.preventDefault();
	const {
		dispatch,
		form
	} = this.props;
	form.validateFields((err, fieldsValue) => {
		if(err) return;
		const values = { ...fieldsValue,
		};
		this.setState({
			formValues: values,
		});
		if(values.operatorName == undefined) values.operatorName = "";
		//签到配置
		dispatch({
			type: 'signin/findInvestor',
			payload: { ...values
			}
		});
	});
};

  handleModalVisible = (flag,record,title) => {
  	if(flag==false){
  		this.setState({
	      modalVisible: flag,
	    });
  	}else{
  		var obj="";
	  	imageUrl="";
	  	if(title!="新建"){
	  		if(record.icon!=undefined){
				imageUrl=record.icon;
			}
	  		record.state+='';
	  		record.hortationType+='';
	  		obj=record;
	  	}
	    this.setState({
	      modalVisible: !!flag,
	      title: title,
	      obj: obj,
	    });
  	}

  };
	/*新增,修改*/
  handleAdd = (title,Id,fields) => {
  	if(title=="新建"){
  			this.props.dispatch({
	      type: 'signin/addsign',
	      payload: {...fields,},
	      callback: (res,resMsg) => {
	      	if(res==1){
	      		message.success(resMsg);
	      	}else{
	      		message.error(resMsg);
	      	}
	      },
	    });
  	}else if(title=="编辑"){
  		this.props.dispatch({
  			type: 'signin/updatesign',
	      payload: {
	      	...fields,
	      	signinConfigId:Id,
	      },
	      callback: (res,resMsg) => {
	      	if(res==1){
	      		message.success(resMsg);
	      	}else{
	      		message.error(resMsg);
	      	}
	      },
	    });
  	}

    this.setState({
      modalVisible: false,
    });
  };

  onSearch=(value)=>{
  	this.props.dispatch({
  			type: 'signin/addsignss',
	      payload: {
	      	signinConfigId:value,
	      },
	      callback: (res,resMsg) => {
	      	if(res==1){
	      		message.success(resMsg);
	      	}else{
	      		message.error(resMsg);
	      	}
	      },
	    });
  }

  	/*删除*/
 	confirmModel=(title,Id)=>{
 		const { dispatch } = this.props;
    	const { selectedRows } = this.state;
	    if(Id==undefined&&Object.keys(selectedRows).length==0){
	    	message.info("还未选择项");
	    }else{
	    	var Ids=[];
		    if(Id!=undefined){
		    	Ids=Id;
		    }else if(selectedRows!=null){
		    	Ids.push(selectedRows.map(row => row.signinConfigId).join(','));
		    }
		    if(title=="删除"){
		    	console.log(Ids);
		    	Modal.confirm({
				    title: '是否删除当前数据选中',
				    content: '',
				     onOk() {
				    	dispatch({
				      	type: 'signin/slesign',
					      payload: {signinConfigIds:Ids,},
					      callback: (res,resMsg) => {
					      	if(res==1){
					      		message.success(resMsg);
					      	}else{
					      		message.error(resMsg);
					      	}
					      },
					  	});
				    },
				});
		    }

	    }
 	}
		renderSimpleForm() {
	    const { getFieldDecorator } = this.props.form;
	    return (
	    	<Col md={20} sm={24}>
	      	<Form onSubmit={this.handleSearch} layout="vertical">
	            <FormItem >
	              {getFieldDecorator('name')(
	                 <Search placeholder="签到码扫码"  enterButton="签到" size="large" onSearch={this.onSearch}
	                 style={{width:'100%'}}
	                 />
	              )}
	            </FormItem>
	      </Form>
	    </Col>
	  );
	}


  render() {
    const { signin: { data }, loading } = this.props;
    const { selectedRows, modalVisible,title,obj } = this.state;
    const columns = [
    	{
		title: '序号',
		dataIndex: 'signinConfigId',
		key: 'signinConfigId',
		width:'70px',
		render: (text, record, index) => { return index + 1 }
		},
		{
		title: '号数',
		dataIndex: 'numberDay',
		width:'70px',
		},
		{
		title: '奖励类型',
		dataIndex: 'hortationType',
		width:'100px',
		},
		{
		title: '图标',
		dataIndex: 'icon',
		width:'70px',
		render: val => <img src={val} style={{width:'50px'}} />,
		},
		{
		title: '奖励',
		dataIndex: 'hortation',
		width:'70px',
		},
		{
		title: '状态',
		dataIndex: 'state',
		width:'70px',
		render: (text, record, index) =>{
				if(record.state==1){
					return "有效"
				}else if(record.state==0){
					return "无效"
				}
			}
		},
		{
		title: '备注',
		dataIndex: 'remark',
		width:'70px',
		},
		{
	    title: '操作',
	    width:'120px',
	    render: (text, record, index) =>{
			return <div>
				<a href="javascript:;" onClick={() => this.handleModalVisible(true,record,'编辑')}>编辑</a>
	    	</div>
	    }
	    },
	];
    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      confirmModel:this.confirmModel,
    };

    return (
    	<PageHeaderLayout title="前台系统/签到配置">
      <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}></div>
            <div className={styles.submitButtons}>
	            	{<Button type="primary" onClick={() => this.handleModalVisible(true,'','新建')}>新建</Button>}
	              {<Button type="primary" onClick={() => this.confirmModel('删除')}>删除</Button>}
	          </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        <CreateForm {...parentMethods} modalVisible={modalVisible} title={title} obj={obj}/>
      </Card>
      </PageHeaderLayout>
    );
  }
}
